﻿#include "../../libcat/include/cat-module.hpp"
#include "../../libcat/include/util/json.h"
#include "../../liblive2d/include/catlive2d.hpp"

namespace {
	sf::Text textForLock;
	long long count = 0;
	int keyCountRecord[100];
	sf::Clock timer;
	int kpsid = 0;
	int kps = 0;

	int windowWidth = 0 , windowHeight = 0;
}

void* Init(cat_data_t* settings) {
	timer.restart();
	count = 0;
	return settings;
}

void* Update(cat_data_t* settings) {
	timer.restart();
	count = 0;
	return settings;
}

void* Release() {
	count = 0;
	return NULL;
};

void* Run(void* _window) {
	cat_window* cwindow = (cat_window*)_window;

	if (timer.getElapsedTime() > sf::seconds(0.2)) {
		timer.restart();
		if (kpsid > 100)
			kpsid = 0;

		keyCountRecord[kpsid] = count;

		if (kpsid < 5) {
			kps = keyCountRecord[kpsid] -
				keyCountRecord[100 -(5 - kpsid)];
		}
		else {
			kps = keyCountRecord[kpsid] -
				keyCountRecord[kpsid - 5];
		}
		kpsid++;
	}

	textForLock.setFont(*cwindow->catfont);
	textForLock.setFillColor(sf::Color(255, 126, 126));
	textForLock.setCharacterSize(100);
	textForLock.setPosition(sf::Vector2f(10,0));
	textForLock.setString(std::to_string(kps));
	
	cwindow->window->draw(textForLock);

	return _window;
};

void * OnMouseClick(const cat_mouse_click_event* event, bool key_up)
{
	if(!key_up)
		count++;
	return NULL;
}

void* OnKeyPress(const cat_key_event* event, bool key_up)
{
	if (!key_up)
		count++;
	return NULL;
}

CAT_DECLARE_MODULE()
bool cat_module_load (){
	cat_source_info a {};
	a.id = 6;
	a.type = CAT_SOURCE_TYPE_INPUT;
	a.Init = Init;
	a.Update = Update;
	a.Release = Release;
	a.Run = Run;
	a.OnMouseClick = OnMouseClick;
	a.OnKeyPress = OnKeyPress;

	cat_register_source(&a);
	return true;
}
